package net.csdn.business.common.domain;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.csdn.business.common.constant.CommonConstants;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author likun
 * @date 2022/6/8 18:52
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageDto<T> implements Serializable {
    private Integer pageNum;

    private Integer pageSize;

    private Long total;

    private Integer pageCount;

    private List<T> content;

    public static <T> PageDto<T> build(Integer pageNum, Integer pageSize) {

        return new PageDto<>(pageNum, pageSize, 0L, 0, new ArrayList<>());
    }

    public static <T> PageDto<T> build() {
        return new PageDto<>(0, 0, 0L, 0, Lists.newArrayList());
    }

    public static <T> PageDto<T> build(List<T> content, Integer page, Integer size, Long total) {
        PageDto<T> result = new PageDto<>();
        result.setContent(content);
        result.setPageNum(Math.toIntExact(page));
        result.setPageSize(Math.toIntExact(size));
        result.setPageCount((int) Math.ceil((double) total / (double) size));
        result.setTotal(total);

        return result;
    }

    public static <T> PageDto<T> build(IPage<T> page) {
        return PageDto.build(page.getRecords(), ((int) page.getCurrent()), ((int) page.getSize()), page.getTotal());
    }

    public void initPage(Integer pageNum, Integer pageSize, Number total) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.pageCount = (int) Math.ceil((double) total.intValue() / (double) pageSize);
        this.total = total.longValue();
    }

    public static int getPage(int page, int maxPage) {
        return Math.min(Math.max(CommonConstants.INT_ONE, page), maxPage);
    }


    public static int getPageSize(int pageSize, int maxPageSize) {
        return Math.max(Math.min(maxPageSize, pageSize), CommonConstants.INT_ONE);
    }

    public static int getPage(int page) {
        return getPage(page, 500);
    }

    public static int getPageSize(int pageSize) {
        return getPageSize(pageSize, 100);
    }
}